/*
 * @Author: your name
 * @Date: 2022-03-22 11:44:23
 * @LastEditTime: 2022-04-03 20:11:34
 * @LastEditors: Please set LastEditors
 * @Description: 上传图片至OSS服务器
 * @FilePath: \blog-system-serve\Routes\upload.js
 */
const express = require("express");
const upload = express.Router();
const multer = require("multer");
const path = require("path");
const file = require("fs");
const client = require("../OSS/index");
const uuid = require("uuid-v4");

// Generate a new UUID

const uploadConfig = multer({
  dest: path.join(__dirname, "../", "public"),
});
const publicPath = path.join(__dirname, "../", "public");

upload.post("/file-upload", uploadConfig.single("file"), async (req, res) => {
  const str = req.body.picUrl;
  // 将服务器已经存在的原图片删除,由uuid生成的链接不重复,不会存在相同图片不显示问题
  if (str) {
    const originUrl = `/img${str.split("/img")[1]}`;
    await client.delete(originUrl, {});
  }

  file.rename(
    req.file.path,
    `${publicPath}/${req.file.originalname}`,
    async (err) => {
      if (err) throw err;
      else {
        const myUUID = uuid();
        let result = await client.put(
          `img/${myUUID}${req.file.originalname}`,
          `${publicPath}/${req.file.originalname}`
        );
        res.send({
          url: result.url,
          name: result.name,
          message: "上传成功",
        });
      }
    }
  );
});
module.exports = upload;
